import mongoose from 'mongoose'
import fs from 'fs' 
import { resolve } from 'path'
import config from '../config'
import Province from '../database/schema/province'
import City from '../database/schema/city'
import Menu from '../database/schema/menu'
// const models = resolve(__dirname, '../database/schema')
// fs.readdirSync(models)
//   .filter(file => ~file.search(/^[^\.].*\.js$/))
//   .forEach(file => require(resolve(models, file)))

const provinceJson = require(resolve(__dirname, '../../json/province.json'))
const cityJson = require(resolve(__dirname, '../../json/city.json'))

const menuJson = require(resolve(__dirname, '../../json/menu.json'))

export const database = app => {
  mongoose.connect(config.db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
  })
  mongoose.connection.on('disconnected', ()=> {
    mongoose.connect(config.db)
  })
  mongoose.connection.on('error', err => {
    console.error(err)
  })
  mongoose.connection.on('open', async () => {
    console.log('成功连接', config.db)
    let province = await Province.find({}).exec()
    if (!province.length) {
      console.log(`插入全国省份城市数据`)
      await Province.insertMany(provinceJson)
    }

    let city = await City.find({}).exec()
    if (!city.length) {
      console.log(`插入全国城市数据`)
      await City.insertMany(cityJson)
    }

    let menu = await Menu.find({}).exec()
    if (!menu.length) {
      console.log(`插入菜单数据`)
      await Menu.insertMany(menuJson)
    }
  })
}